import re

from django.shortcuts import render, redirect, reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_protect
from django.http import HttpResponseForbidden, JsonResponse
from django.contrib.auth import logout, authenticate, login
from django.db import DatabaseError

from .models import User, Application

# Create your views here.

"""
    实现不同用户登录后进入不同页面
    1.登陆操作模块化
    2.根据用户身份进行区分操作
"""


# 模块化登录操作
def my_signin(request, user):
    # 状态保持
    login(request, user)

    # 获取next参数
    print(request.GET)
    next = request.GET.get('next')
    print(next)
    # 如果next 存在则重定向至next
    if next:
        response = redirect(next)
    # 否则重定向至首页
    else:
        if user.identity == User.VISITOR or user.identity == User.UNSURE:
            response = redirect(reverse('contents:index'))
        elif user.identity == User.HOTEL:
            response = redirect(reverse('hotel:index'))
        elif user.identity == User.TOUR_CORP:
            response = redirect(reverse('corp:index'))
        else:
            response = redirect('/admin/')

    # 设置cookie
    response.set_cookie('username', user.username, max_age=3600)
    # 设置cookie时若值是中文则出错
    # response.set_cookie('nickname', user.nickname, max_age=3600)
    # 设置session有效时长
    request.session.set_expiry(3600)
    # 添加session信息
    request.session['username'] = user.username
    request.session['nickname'] = user.nickname
    request.session['identity'] = user.identity

    return response


class LoginView(View):
    """
        用户登录视图
    """

    def get(self, request):
        return render(request, 'login/login.html')

    @method_decorator(csrf_protect)
    def post(self, request):
        """登录逻辑"""
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 校验参数
        if not all([username, password]):  # 校验是否有参数缺失
            return HttpResponseForbidden("缺少必传参数")

        # 相关参数正则校验
        # if not re.match(r'^[a-zA-Z0-9_\u4e00-\u9fa5\s·]+$', username):
        #     return HttpResponseForbidden("用户名不能有特殊字符")
        if not re.match(r'^[\S]{6,12}$', password):
            return HttpResponseForbidden("密码必须6到12位，且不能出现空格")

        # 认证用户
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login/login.html', {'login_errmsg': '账号或密码错误'})

        # 登录（状态保持并并返回响应）
        response = my_signin(request, user)

        # 返回响应
        return response


# # ajax验证
# @csrf_protect
# def verify_account(request):
#     username = request.POST.get('username')
#     password = request.POST.get('password')
#
#     # 查询用户
#     try:
#         db_user = User.objects.get(username=username)
#     except User.DoesNotExist as e:
#         response_data = {'info': 'username_or_password_false'}
#         return JsonResponse(response_data, charset='utf-8')
#
#     # 验证密码
#     if not db_user.check_password(password):
#         response_data = {'info': 'username_or_password_false'}
#         return JsonResponse(response_data, charset='utf-8')
#     else:
#         response_data = {'info': 'true'}
#         return JsonResponse(response_data, charset='utf-8')


# 退出方法
@csrf_protect
def quit(request):
    # 清除状态信息(清楚session数据)
    logout(request)
    # 删除cookie中的username
    response = redirect(reverse('contents:index'))
    response.delete_cookie('username')
    return response


def create_user(username, password, nickname, email, phone, identity):
    # 保存用户数据
    try:
        # 注意：这里需要用create_user,加密存储数据
        user = User.objects.create_user(username=username, password=password,
                                        nickname=nickname, email=email, phone=phone, identity=identity)
        return user
    except DatabaseError:
        return None


class RegisterView(View):
    """
        注册视图
    """

    def get(self, request):
        return render(request, 'login/register.html')

    @method_decorator(csrf_protect)
    def post(self, request):
        # 接收参数
        identity = request.POST.get('identity')
        username = request.POST.get('username')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        phone = request.POST.get('phone')
        email = request.POST.get('email')

        # 从前端传过来的identity时字符串数据，必须先转换成整数类型
        # print(type(identity))
        identity = int(identity)
        # print(type(identity))

        # 校验是否缺少必传参数
        if not all([identity, username, nickname, password, password2, phone, email]):
            return HttpResponseForbidden("缺少必传参数")

        # 正则校验
        if not re.match(r'^[a-zA-Z0-9_\u4e00-\u9fa5\s·]+$', username):
            return HttpResponseForbidden("用户名不能有特殊字符")
            # if not re.match(r'',nickname):
            #     pass
        if not re.match(r'^[\S]{6,12}$', password):
            return HttpResponseForbidden("密码必须6到12位，且不能出现空格")
        if password2 != password:
            return HttpResponseForbidden("两次输入密码不一致")
        if not re.match(
                r'^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$',
                phone):
            return HttpResponseForbidden("请输入正确的手机号")
        if not re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', email):
            return HttpResponseForbidden("请输入合法邮箱")

        # 针对不同类型用户执行不同操作
        if identity == User.VISITOR:
            # 若是旅客,直接注册
            user = create_user(username=username, nickname=nickname, password=password,
                               email=email, phone=phone, identity=identity)
        elif identity == User.TOUR_CORP or identity == User.HOTEL or identity == User.ADMINISTRATOR:
            # 若是旅游公司或宾馆
            # 先将身份设置为待完善
            user = create_user(username=username, nickname=nickname, password=password,
                               email=email, phone=phone, identity=User.UNSURE)
            print(user.id)
            # 生成注册申请
            Application.objects.create(applicant=user, identity=identity, state=Application.PENDING)
            # 提醒该用户账户类型待完善

        else:
            return HttpResponseForbidden("输入用户身份不合法")

        if not user:
            return render(request, 'login/register.html', {'register_errmsg': '注册失败'})

        # 登录（状态保持并并返回响应）
        response = my_signin(request, user)

        # 返回响应
        return response


class UsernameCountView(View):
    """
        验证用户名是否重复注册
    """

    @method_decorator(csrf_protect)
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({
            'count': count,
        })


class PhoneCountView(View):
    """
        验证手机号是否重复
    """

    @method_decorator(csrf_protect)
    def get(self, request, phone):
        count = User.objects.filter(phone=phone).count()
        return JsonResponse({
            'count': count,
        })


class EmailCountView(View):
    """
        验证邮箱是否重复
    """

    @method_decorator(csrf_protect)
    def get(self, request, email):
        count = User.objects.filter(email=email).count()
        # print(count)
        return JsonResponse({
            'count': count,
        })
